//
//  AllParksMapViewController.m
//  HundPark
//
//  Created by Aguilar Rolando on 2013-03-12.
//  Copyright (c) 2013 ARV IT. All rights reserved.
//

#import "AllParksMapViewController.h"


@interface AllParksMapViewController (){

}

@property(weak,nonatomic) City *allParks;
- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender;

@end

@implementation AllParksMapViewController

@synthesize mapView = _mapView;
@synthesize allParks =_allParks;
@synthesize park =_park;

#define MAPMARGINS 1.5
#define OVERLAY_RADIUS 250.0
#define GOOGLE_MAP_URL @"http://maps.google.com/maps?saddr=Current+Location&daddr=%f,%f"
#define NAVBAR_IMAGE @"NavBarItem.png"

#pragma mark - Lazy Instantiation

//Lazy Instantiation
-(City *)allParks
{
    if(!_allParks){
        AppDelegate *appDelegate =  (AppDelegate *)[[UIApplication sharedApplication ]delegate];
        _allParks = appDelegate.allParks;
    }
    
    return _allParks;
}

#pragma mark - Life cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    // Set mapview as delegate
    self.mapView.delegate = self;
    
    // CustomLabel
    CustomNavbarTitleLabelGreen *titleLabel =[[CustomNavbarTitleLabelGreen alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
    self.navigationItem.titleView = titleLabel;
    
    // Set up for one park or all parks
    if (self.park) {
        titleLabel.text = self.park.name;
        
        [self.mapView addAnnotation:self.park];
        [self addGeoFanceOverlayForPark:self.park];
        
    } else {
        titleLabel.text = @"Alla Parker";
        
        for (Park *park in self.allParks.parks) {
            [self.mapView addAnnotation:park];
            [self addGeoFanceOverlayForPark:park];
        }
    }
    
    [self zoomToFitMapAnnotations:self.mapView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.mapView.showsUserLocation= NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.mapView.showsUserLocation= YES;
}

-(void)addGeoFanceOverlayForPark: (Park*) park{

    // Add overlay circle with center at touch point and radius
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:park.coordinate
                                                     radius:OVERLAY_RADIUS];
    circle.title = @"Geofence";
    
    // Add overlay circle
    [self.mapView addOverlay:circle];
}

// Zoom fit map for current position and park coordinate
-(void)zoomToFitMap:(MKMapView*)mapView{
    
    // Get Map Point
    MKMapPoint annotationPoint = MKMapPointForCoordinate(self.park.coordinate);
    MKMapPoint userLocationPoint = MKMapPointForCoordinate(mapView.userLocation.coordinate);
	
    // Create Rect
    MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
    MKMapRect userLocationPointRect = MKMapRectMake(userLocationPoint.x, userLocationPoint.y, 0.1, 0.1);
	
    // Union both rects 
    MKMapRect zoomRect = MKMapRectUnion(userLocationPointRect, annotationRect);
    
    [self setMapPosition:zoomRect];
}

// Zoom fit map for all park annotation. Current location not included
-(void)zoomToFitMapAnnotations:(MKMapView*)mapView{
    
    // Collects all create Rect for every annotation in map
    MKMapRect zoomRect = MKMapRectNull;
    for (id <MKAnnotation> annotation in mapView.annotations)
    {
        MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
        MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
        zoomRect = MKMapRectUnion(zoomRect, pointRect);
    }
    
    [self setMapPosition:zoomRect];
}

- (void)setMapPosition:(MKMapRect)zoomRect {
    // Adjust United Annotation Rect
    double w = MKMapRectGetWidth(zoomRect)*MAPMARGINS;
    double h = MKMapRectGetHeight(zoomRect)*MAPMARGINS;
    double centerX = MKMapRectGetMidX(zoomRect);
    double centerY = MKMapRectGetMidY(zoomRect);
	
    // Get New Center point of Rect
    double x = centerX - w/2;
    double y = centerY - h/2;
    MKMapRect fitedRect = MKMapRectMake(x, y, w, h);
    
    // Display the new potion of the map
    [self.mapView setVisibleMapRect:fitedRect animated:YES];
}

#pragma mark - Mapview delegate
- (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id<MKAnnotation>)annotation {
    
    if (annotation == aMapView.userLocation) {
        return nil; // Let map view handle user location annotation
    }
    
    // Identifier for reusing annotationviews
    static NSString *annotationIdentifier = @"icon_annotation";
    
    // Check in queue if there is an annotation view we already can use, else create a new one
    AWIconAnnotationView *annotationView = (AWIconAnnotationView *)[aMapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
    if (!annotationView) {
        annotationView = [[AWIconAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:annotationIdentifier];
        annotationView.canShowCallout = YES;
        
        // Displays new view, displays info about the park
        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        // Opens ios Maps or google maps to display direction to park
        UIButton *openMaps = [UIButton buttonWithType:UIButtonTypeCustom];
        openMaps.frame = CGRectMake(0, 0, 23, 23);
        [openMaps setImage:[UIImage imageNamed:NAVBAR_IMAGE] forState:UIControlStateNormal];
        annotationView.leftCalloutAccessoryView = openMaps;
    }
    return annotationView;
}

// On Accesssory click display direction
// Open native map for iOS6
// Open Gooogle maps for iOS5 and lower
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    // Get Clicked annotation
    Park *selectedAnnotationPark = (Park*)view.annotation;
    
    if (control == view.leftCalloutAccessoryView) {
        // create MKMapItem out of coordinates
        MKPlacemark *placeMark = [[MKPlacemark alloc] initWithCoordinate:selectedAnnotationPark.coordinate addressDictionary:nil];
        MKMapItem *destination =  [[MKMapItem alloc] initWithPlacemark:placeMark];
        
        if([destination respondsToSelector:@selector(openInMapsWithLaunchOptions:)])
        {
            // using iOS6 native maps app
            [destination openInMapsWithLaunchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving}];
            
        } else{
            
            // using iOS 5 which has the Google Maps application
            NSString* url = [NSString stringWithFormat: GOOGLE_MAP_URL, selectedAnnotationPark.coordinate.latitude,selectedAnnotationPark.coordinate.longitude];
            [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
        }
    }
    else if (control == view.rightCalloutAccessoryView)
    {
        // Segue to park detail
        [self performSegueWithIdentifier:@"parkInfoDetail" sender:selectedAnnotationPark];
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    // Fit map for ome park
    if(self.park){
        [self zoomToFitMap:self.mapView];
    }
}

#pragma mark - Actions

- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender{
    // Otherwise gestures is called twice
    if (sender.state == UIGestureRecognizerStateBegan){
        // Get touch point location
        CGPoint touchPoint = [sender locationInView:self.mapView];
        
        // Convert point
        CLLocationCoordinate2D touchCoordinate = [self.mapView convertPoint:touchPoint
                                                       toCoordinateFromView:self.mapView];
        
        // CLLocationCoordinate2D -> NSValue
        NSValue *touchCoordinateValue = [NSValue valueWithMKCoordinate:touchCoordinate];
        [self performSegueWithIdentifier:@"addParken" sender:touchCoordinateValue];
    }
}


- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    if ([overlay isKindOfClass:[MKCircle class]]) {
        // Set up circle
        MKCircleView *circleView = [[MKCircleView alloc] initWithCircle:(MKCircle*)overlay];
        circleView.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
        circleView.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.7];
        circleView.lineWidth = 2;
        return circleView;
    }
    return nil;
}


#pragma mark - Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:@"addParken"]) {
        
        UINavigationController *navc = segue.destinationViewController;
        AddParkTableViewController *addParkViewController = (AddParkTableViewController *)navc.topViewController;
        
        //Check that we expect an NSValue class
        if ([sender isKindOfClass:[NSValue class]]) {
            //From NSValue -> CLLocationCoordinate2D
            addParkViewController.coordinate = [sender MKCoordinateValue];
            addParkViewController.delegate = self;
        }
    }
    
    if ([segue.identifier isEqualToString:@"parkInfoDetail"]) {
        
        ParkDetailViewController *parkViewController = segue.destinationViewController;
        
        // Check that we expect an Park class
        if([sender isKindOfClass:[Park class]])
        {
            // Create object Park
            Park *selectedPark = sender;
            parkViewController.park = selectedPark;
        }
    }
}

- (IBAction)cancelFromSegue:(UIStoryboardSegue *)segue {
    
    
}


#pragma mark AddParkController delegate
- (void)addParkControllerDidFinish:(AddParkTableViewController *)controller park:(Park *) addedPark;
{
    // Before adding new park as annontation to mapview get newly created parkId
    [self.mapView addAnnotation:addedPark];

    [self addGeoFanceOverlayForPark:addedPark];
    
    // Close modal view
    [self dismissViewControllerAnimated:YES
                             completion:nil];
}

@end
